<style lang="less">
  @import './own-space.less';
  @import '../styles/common.less';
</style>

<template>
  <div>
    <Card>
      <p slot="title">
        <Icon type="person"></Icon>
        个人信息
      </p>
      <div>
        <Form
          ref="userForm"
          :model="userInfoObj"
          :label-width="100"
          label-position="right"
          :rules="inforValidate"
        >
          <FormItem label="头像：">
            <img :src="avatar" alt="头像" style="width: 50px;height: 50px;" v-if="avatar">
            <Button type="text" size="small" @click="updateImage">设置头像</Button>
            <input type="file" id="avatar_file" style="display: none;"
                   accept="image/*"
                   @change="sendFileClick()"/>
          </FormItem>
          <FormItem label="用户姓名：" prop="name">
            <div style="display:inline-block;width:300px;">
              <Input v-model="userInfoObj.name"></Input>
            </div>
          </FormItem>
          <FormItem label="用户手机：">
            <span>{{ userInfoObj.mobile }}</span>
            <Button type="text" size="small" @click="showEditMobile">修改手机号</Button>
          </FormItem>
          <FormItem label="办公电话：" prop="landline">
            <div style="display:inline-block;width:300px;">
              <Input v-model="userInfoObj.landline"></Input>
            </div>
          </FormItem>
          <FormItem label="性别：">
            <span>{{ userInfoObj.sex }}</span>
          </FormItem>
          <FormItem label="部门：">
            <span>{{ userInfoObj.department }}</span>
          </FormItem>
          <FormItem label="登录密码：">
            <Button type="text" size="small" @click="showEditPassword">修改密码</Button>
          </FormItem>
          <FormItem label="前台系统版本：">
            <span>v {{ version }}</span>
          </FormItem>
          <FormItem label="后台系统版本：" v-if="version_backend">
            <span>v {{ version_backend }}</span>
          </FormItem>
          <div>
            <!--<Button type="text" style="width: 100px;" @click="cancelEditUserInfor">取消</Button>-->
            <Button type="primary" style="width: 100px;" :loading="save_loading" @click="saveInfoAjax">保存</Button>
          </div>
        </Form>
      </div>
    </Card>
    <Modal v-model="editPhoneModal" :closable='false' :mask-closable=false :width="500">
      <h3 slot="header" style="color:#2D8CF0">修改手机号</h3>
      <Form ref="editPhoneForm" :model="editPhoneForm" :label-width="100" label-position="right"
            :rules="PhoneValidate">
        <FormItem label="新手机号" prop="mobile">
          <Input v-model="editPhoneForm.mobile" placeholder="请输入新手机号"></Input>
        </FormItem>
        <FormItem label="验证码" prop="mobileCode">
          <Input v-model="editPhoneForm.mobileCode" placeholder="请输入验证码"></Input>
        </FormItem>
        <FormItem label="">
          <Button @click="getIdentifyCodePhone"
                  :disabled="canGetIdentifyCodePhone">{{ gettingIdentifyCodeBtnContentPhone }}
          </Button>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="cancelEditMobile">取消</Button>
        <Button type="primary" :loading="savePassLoading" @click="saveEditPhone">保存</Button>
      </div>
    </Modal>
    <Modal v-model="editPasswordModal" :closable='false' :mask-closable=false :width="500">
      <h3 slot="header" style="color:#2D8CF0">修改密码</h3>
      <Form ref="editPasswordForm" :model="editPasswordForm" :label-width="100" label-position="right"
            :rules="passwordValidate">
        <FormItem label="验证码" prop="Code" :error="CodeError">
          <Input v-model="editPasswordForm.Code" placeholder="请输入验证码"></Input>
        </FormItem>
        <FormItem label="">
          <Button @click="getIdentifyCode"
                  :disabled="canGetIdentifyCode">{{ gettingIdentifyCodeBtnContent }}
          </Button>
        </FormItem>
        <FormItem label="新密码" prop="newPass">
          <Input v-model="editPasswordForm.newPass" placeholder="请输入新密码，至少6位字符"></Input>
        </FormItem>
        <FormItem label="确认新密码" prop="rePass">
          <Input v-model="editPasswordForm.rePass" placeholder="请再次输入新密码"></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="cancelEditPass">取消</Button>
        <Button type="primary" :loading="savePassLoading" @click="saveEditPass">保存</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  import Cookies from 'js-cookie';
  import Util from '../../libs/util';
  import Utils from '../../libs/mod.utils';
  import Nim from '../../libs/mod.nim';
  export default {
    name: 'ownspace_index',
    data () {
      const validePhone = (rule, value, callback) => {
        var re = /^1[0-9]{10}$/;
        if (!re.test(value)) {
          callback(new Error('请输入正确格式的手机号'));
        } else {
          callback();
        }
      };
      const valideRePassword = (rule, value, callback) => {
        if (value !== this.editPasswordForm.newPass) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback();
        }
      };
      return {
        version: '',
        version_backend: '',
        userInfoObj: {
          name: '',
          mobile: '',
          landline: '',
          sex: '',
          department: '',
        },
        avatar: '',// 头像
        uid: '', // 登录用户的userId
        securityCode: '', // 验证码
        phoneHasChanged: false, // 是否编辑了手机
        save_loading: false,
        identifyError: '', // 验证码错误
        editPasswordModal: false, // 修改密码模态框显示
        editPhoneModal: false, // 修改手机号模态框显示
        savePassLoading: false,
        CodeError: '',
        CodeErrorPhone: '',
        hasGetIdentifyCode: false, // 是否点了获取验证码
        canGetIdentifyCode: false, // 是否可点获取验证码
        hasGetIdentifyCodePhone: false, // 是否点了获取验证码
        canGetIdentifyCodePhone: false, // 是否可点获取验证码
        checkIdentifyCodeLoading: false,
        inforValidate: {
          name: [
            {required: true, message: '请输入姓名', trigger: 'blur'}
          ],
        },
        editPhoneForm: {
          mobile: '',
          mobileCode: ''
        },
        PhoneValidate: {
          mobileCode: [
            {required: true, message: '请输入验证码', trigger: 'blur'},
          ],
          mobile: [
            {required: true, message: '请输入手机号码', trigger: 'blur'},
            {validator: validePhone}
          ],
        },
        editPasswordForm: {
          Code: '',
          newPass: '',
          rePass: ''
        },
        passwordValidate: {
          Code: [
            {required: true, message: '请输入验证码', trigger: 'blur'}
          ],
          newPass: [
            {required: true, message: '请输入新密码', trigger: 'blur'},
            {min: 6, message: '请至少输入6个字符', trigger: 'blur'},
            {max: 32, message: '最多输入32个字符', trigger: 'blur'}
          ],
          rePass: [
            {required: true, message: '请再次输入新密码', trigger: 'blur'},
            {validator: valideRePassword, trigger: 'blur'}
          ]
        },
        inputCodeVisible: false, // 显示填写验证码box
        inputCodeVisiblePhone: false, // 显示填写验证码box
        initPhone: '',
        gettingIdentifyCodeBtnContent: '获取验证码', // “获取验证码”按钮的文字
        gettingIdentifyCodeBtnContentPhone: '获取验证码', // “获取验证码”按钮的文字
      };
    },
    created: function () {
      var _this = this;
      _this.init();
      var version = Util.version;
      _this.version = version;

      _this.get_version_backend();
    },
    mounted () {
      var _this = this;
    },
    methods: {
      init () {
        var _this = this;
        var userInfo = localStorage.getItem('userInfo');
        if (userInfo && userInfo != '') {
          var userInfoObj = Util.toJson(userInfo);
          var name = userInfoObj.name;
          var mobile = userInfoObj.mobile;
          var landline = userInfoObj.landline;
          var sex = userInfoObj.sex;
          var avatar = userInfoObj.avatar;
          var thumb = avatar.thumb ? avatar.thumb : '/vendors/images/person.png';
          _this.avatar = thumb;
          _this.$store.commit('setAvator', thumb);
          if (sex == 'male') {
            sex = '男';
          } else if (sex == 'female') {
            sex = '女';
          }
          var dep = [];
          var departments = userInfoObj.departments;
          for (var k in departments) {
            if (!departments[k]) {
              continue;
            }
            var dname = departments[k].name;
            dep.push(dname);
          }
          _this.uid = userInfoObj.id;
          _this.userInfoObj.name = name;
          _this.userInfoObj.mobile = mobile;
          _this.userInfoObj.landline = landline;
          _this.userInfoObj.sex = sex;
          _this.userInfoObj.department = dep.join(' ， ');
        }

      },
      // 后台版本号
      get_version_backend: function () {
        var _this = this;
        var data = {};
        var params = {
          url: '/version',
          type: Util.method.post,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            _this.version_backend = res.data;
          }
        }
      },
      updateImage: function () {
        var _this = this;
        document.getElementById('avatar_file').click();
      },
      sendFileClick: function () {
        var _this = this;
        var __this = document.getElementById("avatar_file");
        var fileObj = __this.files[0];

        var formData = new FormData();
        formData.append("file", fileObj);
        formData.append("type", 'image');
        var params = {
          url: '/file/addImage',
          type: Util.method.post,
          data: formData,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var data = res.data;
            var id = data.id;
            var name = data.name;
            var thumb = data.thumb;
            var url = data.url;
            _this.updateImg(id);
          } else {
            _this.$Message.error('上传失败!');
          }
        }
      },
      updateImg: function (id) {
        var _this = this;
        var data = {
          id: _this.uid,
          avatar: id,
        };
        var params = {
          url: '/user/update',
          type: Util.method.post,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || {};
            localStorage.setItem('userInfo', Util.toStr(_data));
            var userName = _data.name;
            var avatar = _data.avatar;
            var thumb = avatar.thumb ? avatar.thumb : '/vendors/images/person.png';
            _this.avatar = thumb;
            _this.$store.commit('setAvator', thumb);
            _this.$Message.success('设置头像成功!');
          } else {
            _this.$Message.error('设置头像失败!');
          }
        }
      },
      getIdentifyCode () {
        var _this = this;
        _this.hasGetIdentifyCode = true;
        var data = {
          mobile: _this.userInfoObj.mobile,
        };
        var params = {
          url: '/user/captcha',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var data = res.data;
            _this.canGetIdentifyCode = true;
            let timeLast = 60;
            let timer = setInterval(() => {
              if (timeLast >= 0) {
                _this.gettingIdentifyCodeBtnContent = timeLast + '秒后重试';
                timeLast -= 1;
              } else {
                clearInterval(timer);
                _this.gettingIdentifyCodeBtnContent = '获取验证码';
                _this.canGetIdentifyCode = false;
              }
            }, 1000);
            _this.inputCodeVisible = true;
          } else {
            _this.hasGetIdentifyCode = false;
            _this.$Message.error('发送验证码失败!');
          }
        }
      },
      showEditPassword () {
        this.editPasswordModal = true;
      },
      cancelEditPass () {
        this.editPasswordModal = false;
      },
      getIdentifyCodePhone: function () {
        var _this = this;
        var mobile = _this.editPhoneForm.mobile;
        if (mobile == '') {
          _this.$Message.error('请填写新手机号!');
          return false;
        }
        if (!Util.checkMobile(mobile)) {
          _this.$Message.error('手机号格式不正确!');
          return false;
        }
        _this.hasGetIdentifyCodePhone = true;
        var data = {
          mobile: _this.editPhoneForm.mobile,
        };
        var params = {
          url: '/user/captcha',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var data = res.data;
            _this.canGetIdentifyCodePhone = true;
            let timeLast = 60;
            let timer = setInterval(() => {
              if (timeLast >= 0) {
                _this.gettingIdentifyCodeBtnContentPhone = timeLast + '秒后重试';
                timeLast -= 1;
              } else {
                clearInterval(timer);
                _this.gettingIdentifyCodeBtnContentPhone = '获取验证码';
                _this.canGetIdentifyCodePhone = false;
              }
            }, 1000);
            _this.inputCodeVisiblePhone = true;
          } else {
            _this.hasGetIdentifyCodePhone = false;
            _this.$Message.error('发送验证码失败!');
          }
        }
      },
      showEditMobile () {
        this.editPhoneModal = true;
      },
      cancelEditMobile () {
        this.editPhoneModal = false;
      },
      //修改手机号
      saveEditPhone: function () {
        var _this = this;
        _this.$refs['editPhoneForm'].validate((valid) => {
          if (valid) {
            _this.savePassLoading = true;
            // you can write ajax request here
            var data = {
              action: 'telephone',
              id: _this.uid,
              mobile: _this.editPhoneForm.mobile,
              captcha: _this.editPhoneForm.mobileCode,
            };
            var params = {
              url: '/user/update',
              type: Util.method.post,
              data: data,
              success: _successFun
            };
            Util.ajax(_this, params);
            function _successFun(res) {
              _this.savePassLoading = false;
              if (res.result == 0) {
                var data = res.data;
                _this.$Message.success('修改手机号成功，请重新登录!');
                _this.editPhoneModal = false;
                // 退出登录
                Nim.loginOutNimdata();
                _this.$store.commit('logout', _this);
                _this.$store.commit('clearOpenedSubmenu');
                _this.$router.push({
                  name: 'login'
                });
              } else {
                _this.$Message.error('修改手机号失败!');
              }
            }
          }
        });
      },
      //修改密码
      saveEditPass () {
        var _this = this;
        _this.$refs['editPasswordForm'].validate((valid) => {
          if (valid) {
            _this.savePassLoading = true;
            // you can write ajax request here
            var data = {
              action: 'password',
              id: _this.uid,
              mobile: _this.userInfoObj.mobile,
              captcha: _this.editPasswordForm.Code,
              password: _this.editPasswordForm.newPass,
            };
            var params = {
              url: '/user/update',
              type: Util.method.post,
              data: data,
              success: _successFun
            };
            Util.ajax(_this, params);
            function _successFun(res) {
              _this.savePassLoading = false;
              if (res.result == 0) {
                var data = res.data;
                var login_password = Utils.compile(_this.editPasswordForm.newPass);//加密
                Utils.setCookie('login_password', login_password, 30);
                _this.$Message.success('修改密码成功');
                _this.editPasswordModal = false;
              } else {
                _this.$Message.error('修改密码失败!');
              }
            }
          }
        });
      },
      hasChangePhone () {
        this.phoneHasChanged = true;
        this.hasGetIdentifyCode = false;
        this.identifyCodeRight = false;
      },
      saveInfoAjax () {
        var _this = this;
        _this.save_loading = true;
        var data = {
          action: 'name',
          id: _this.uid,
          name: _this.userInfoObj.name,
          landline: _this.userInfoObj.landline,
        };
        var params = {
          url: '/user/update',
          type: Util.method.post,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          _this.save_loading = false;
          if (res.result == 0) {
            var _data = res.data || {};
            localStorage.setItem('userInfo', Util.toStr(_data));
            var userName = _data.name;
            var avatar = _data.avatar;
            var thumb = avatar.thumb ? avatar.thumb : '/vendors/images/person.png';
            _this.$store.commit('setAvator', thumb);
            Cookies.set('user', userName);
            _this.$Message.success('保存成功!');
          } else {
            _this.$Message.error('保存失败!');
          }
        }
      },
      cancelEditUserInfor: function () {
        var _this = this;
        _this.$store.commit('removeTag', 'ownspace_index');
        localStorage.pageOpenedList = JSON.stringify(_this.$store.state.app.pageOpenedList);
        let lastPageName = '';
        if (_this.$store.state.app.pageOpenedList.length > 1) {
          lastPageName = _this.$store.state.app.pageOpenedList[1].name;
        } else {
          lastPageName = _this.$store.state.app.pageOpenedList[0].name;
        }
        _this.$router.push({
          name: lastPageName
        });
      },

    }
  };
</script>
